<template>
  <div class="InfoMainBody">
    <div class="docMain">
      <div class="btn">
        <el-button type="primary" @click="goBack"> 返回 </el-button>
        <div></div>
        <div>
          <el-button type="primary" icon="Document" @click="handleExport"> 导出报告 </el-button>
        </div>
      </div>
      <div class="infoTitle">检查报告</div>
      <div class="tabelLine">
        <div class="tabelItem">编号</div>
        <div class="tabelItem">{{ drawerInfo.number }}</div>
        <div class="tabelItem">检查日期</div>
        <!-- <div class="tabelItem tabelItem1">{{ drawerInfo.date.split(' ')[0] }}</div> -->
        <div class="tabelItem tabelItem1">{{ drawerInfo.date }}</div>
      </div>
      <div class="tabelLine tabelLine1">
        <div class="tabelItem">经纬度</div>
        <div class="tabelItem">{{ drawerInfo.location }}</div>
        <div class="tabelItem">无人机编号</div>
        <div class="tabelItem tabelItem1">{{ drawerInfo.cameraModel }}</div>
      </div>
      <div class="tabelLine tabelLine1" style="border-bottom: 0">问题描述：</div>

      <div class="textarea-with-button">
        <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 30 }" placeholder="展示结果" v-model="drawerInfo.question"></el-input>
        <el-button type="primary" icon="Document" @click="saveExport" class="save-report-button">保存编辑内容</el-button>
      </div>

      <div class="tabelLine tabelLine1" style="height: 618px">
        <div class="miniWindow">
          <div v-show="position != null" class="position-info">
            经度: {{ position.longitude.toFixed(6) }}, 纬度: {{ position.latitude.toFixed(6) }}
          </div>
          <div class="cesium-layer" ref="containerRef">
            <div class="cesium-layer_btn" :class="{ 'active': isActive }" @click="toggleList">
              <layers theme="outline" size="22" fill="#fff" />
            </div>
          </div>
          <div v-if="showList" class="options-list">
            <div class="item" v-for="(item, index) in layerRefs" :key="index">
              <div class="checkBox">
                <label class="neon-checkbox">
                  <input type="checkbox" @click.stop="changelayer(index, item.type)" :checked="item.type" />
                  <div class="neon-checkbox__frame">
                    <div class="neon-checkbox__box">
                      <div class="neon-checkbox__check-container">
                        <svg viewBox="0 0 24 24" class="neon-checkbox__check">
                          <path d="M3,12.5l7,7L21,5"></path>
                        </svg>
                      </div>
                      <div class="neon-checkbox__glow"></div>
                      <div class="neon-checkbox__borders"><span></span><span></span><span></span><span></span></div>
                    </div>
                    <div class="neon-checkbox__effects">
                      <div class="neon-checkbox__particles">
                        <span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span> <span></span
                        ><span></span><span></span><span></span>
                      </div>
                      <div class="neon-checkbox__rings">
                        <div class="ring"></div>
                        <div class="ring"></div>
                        <div class="ring"></div>
                      </div>
                      <div class="neon-checkbox__sparks"><span></span><span></span><span></span><span></span></div>
                    </div>
                  </div>
                </label>
              </div>
              <div style="cursor: pointer" @click.stop="changelayer(index, item.type)">{{ item.name }}</div>
            </div>
          </div>
          <div id="checklist">
            <div class="item" v-for="(item, index) in entityRefs" :key="index">
              <div class="checkBox">
                <label class="neon-checkbox">
                  <input type="checkbox" @click.stop="changeEntity(index, item.type)" :checked="item.type" />
                  <div class="neon-checkbox__frame">
                    <div class="neon-checkbox__box">
                      <div class="neon-checkbox__check-container">
                        <svg viewBox="0 0 24 24" class="neon-checkbox__check">
                          <path d="M3,12.5l7,7L21,5"></path>
                        </svg>
                      </div>
                      <div class="neon-checkbox__glow"></div>
                      <div class="neon-checkbox__borders"><span></span><span></span><span></span><span></span></div>
                    </div>
                    <div class="neon-checkbox__effects">
                      <div class="neon-checkbox__particles">
                        <span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span> <span></span
                        ><span></span><span></span><span></span>
                      </div>
                      <div class="neon-checkbox__rings">
                        <div class="ring"></div>
                        <div class="ring"></div>
                        <div class="ring"></div>
                      </div>
                      <div class="neon-checkbox__sparks"><span></span><span></span><span></span><span></span></div>
                    </div>
                  </div>
                </label>
              </div>
              <div
                style="cursor: pointer"
                :style="{ color: item.isActive ? '#00ffaa' : '#fff' }"
                @click="flyToPosition(item.longitude, item.latitude, item.altitude)"
              >
                {{ item.imgName }}
              </div>
            </div>
          </div>
          <div id="cesiumContainer"></div>
        </div>
      </div>
      <div class="imgLine tabelLine1" style="padding: 10px; box-sizing: border-box">
        <div v-for="(item, index) in drawerInfo.imgList" :key="index" style="position: relative">
          <div class="position-info_item" :key="item.imgName">{{ item.imgName }}</div>
          <img :key="index" :src="item.newImgUrl" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, onBeforeUnmount } from 'vue';
import * as Cesium from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';
import { getUAVcheckInfo, putUAVcheckInfo, exportUAVcheck } from '@/api/aiManage/UAVinspection/index';
import { ElLoading } from 'element-plus';
import gcoord from 'gcoord';
import { Layers } from '@icon-park/vue-next';
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance();
const questionFlag = ref('正在分析问题中，请稍后查看!!!');
const router = useRouter();
const userStore = useUserStore();

// 声明 viewer 的响应式引用
const viewer = ref<Cesium.Viewer>();

// 获取路由参数
const inspectionId = ref(proxy.$route.query.id);

// 详细内容
const drawerInfo = ref({});
const drawerInfoID = ref([]);
const drawerInfoTimer = ref(null);

let handler: Cesium.ScreenSpaceEventHandler | null = null;
const position = ref<{ longitude: number; latitude: number; height: number } | null>({
  longitude: 0,
  latitude: 0,
  height: 0
});
const positiongetFlag = ref(true);
const positiongetTimer = ref(null);

const flyToPositionArr = ref();
const layerRefs = ref([
  { name: '高德影像', type: true },
  { name: '高德注记', type: true }
]); // 存储图层引用
const entityRefs = ref([]); // 存储实体引用

const showList = ref(false);
const isActive = ref(false);
const containerRef = ref(null);
const reSetImage = ref(false);

// 初始化 Cesium 方法
const initCesium = async () => {
  viewer.value = new Cesium.Viewer('cesiumContainer', {
    terrainProvider: new Cesium.EllipsoidTerrainProvider(),
    timeline: false,
    animation: false,
    geocoder: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    baseLayerPicker: false, // 禁用图层选择器
    fullscreenButton: false, // 禁用全屏按钮
    // 禁用所有与选择相关的UI组件
    selectionIndicator: false,
    infoBox: false,
    // 禁用相机跟踪系统
    scene3DOnly: true,
    imageryProvider: false
  });

  // 添加高德影像图层
  const amapImg = new Cesium.UrlTemplateImageryProvider({
    url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
    subdomains: ['1', '2', '3', '4'],
    minimumLevel: 1,
    maximumLevel: 18, // 提升至20级
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    credit: new Cesium.Credit('高德地图'),
    enablePickFeatures: false, // 禁用要素拾取
    rectangle: Cesium.Rectangle.fromDegrees(73.66, 3.86, 135.05, 53.55) // 限定中国区域加载
  });
  // 调整切片请求策略
  // viewer.value.imageryLayers.addImageryProvider(amapImg);

  // 添加高德注记图层
  const amapLabel = new Cesium.UrlTemplateImageryProvider({
    url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
    subdomains: ['1', '2', '3', '4'],
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    maximumLevel: 18
  });
  viewer.value.imageryLayers.addImageryProvider(amapLabel);

  // 启用缓存减少请求
  viewer.value.imageryLayers.addImageryProvider(amapImg, {
    cacheDuration: 24 * 3600 // 24小时缓存
  });

  // 去除默认的点击事件
  viewer.value.scene.screenSpaceCameraController.enableInputs = true;

  // 初始化事件处理器
  handler = new Cesium.ScreenSpaceEventHandler(viewer.value.scene.canvas);

  // 注册左键点击事件
  handler.setInputAction((event: any) => {
    if (positiongetFlag.value) {
      const clickPosition = event.position;
      const pickedObject = viewer.value!.scene.pick(event.position);
      if (!clickPosition) return;

      positiongetFlag.value = false;

      // if (pickedObject) {
      //   reSetImage.value = true;
      //   let array = viewer.value.entities.values;
      //   for (let index = 0; index < array.length; index++) {
      //     array[index]._rectangle.height = 1 - (index + 1) / 10;
      //     if (array[index]._id == pickedObject.id._id) {
      //       array[index]._rectangle.height = array.length / 10;
      //       break;
      //     }
      //   }
      //   // viewer.value.entities.values.forEach((item, index) => {
      //   //   if(item._id == pickedObject.id._id) {
      //   //     item._rectangle.height = 1 - index / 10;
      //   //   }
      //   // });
      //   // entity.height = entityRefs.value.length / 10;
      //   // handleImageClick(entity);
      // } else {
      //   if (reSetImage.value) {
      //     reSetImage.value = false;
      //     viewer.value.entities.values.forEach((item, index) => {
      //       item._rectangle.height = 1 - index / 10;
      //     });
      //   } else {
      //     // 获取笛卡尔坐标
      //     const cartesian = viewer.value!.camera.pickEllipsoid(clickPosition, viewer.value!.scene.globe.ellipsoid);
      //     if (!cartesian) return;
      //     // 转换为经纬度和高度
      //     const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      //     const longitude = Number(Cesium.Math.toDegrees(cartographic.longitude));
      //     const latitude = Number(Cesium.Math.toDegrees(cartographic.latitude));
      //     const height = viewer.value!.scene.globe.getHeight(cartographic) || 0;
      //     let list = transformCoordinate2(longitude, latitude);
      //     position.value = {
      //       longitude: list[0],
      //       latitude: list[1],
      //       height
      //     };
      //   }
      // }

      if (Cesium.defined(pickedObject) && pickedObject.id) {
        reSetImage.value = true;
        // 点击的是实体对象
        const entity = pickedObject.id;

        // 判断是否是图片实体
        if (entity.rectangle && entity.rectangle.material instanceof Cesium.ImageMaterialProperty) {
          // 触发自定义事件
          handleImageClick(entity);
        }
      } else {
        if (reSetImage.value) {
          reSetImage.value = false;
          // 点击空白区域时恢复所有高度
          entityRefs.value.forEach((item) => {
            item.isActive = false;
            item.currentHeight = item.baseHeight;
            const entity = viewer.value!.entities.values.find((e) => e.name === item.imgName);
            if (entity?.rectangle) {
              entity.rectangle.height = new Cesium.ConstantProperty(item.baseHeight);
            }
          });
        } else {
          // 获取笛卡尔坐标
          const cartesian = viewer.value!.camera.pickEllipsoid(clickPosition, viewer.value!.scene.globe.ellipsoid);
          if (!cartesian) return;
          // 转换为经纬度和高度
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const longitude = Number(Cesium.Math.toDegrees(cartographic.longitude));
          const latitude = Number(Cesium.Math.toDegrees(cartographic.latitude));
          const height = viewer.value!.scene.globe.getHeight(cartographic) || 0;
          let list = transformCoordinate2(longitude, latitude);
          position.value = {
            longitude: list[0],
            latitude: list[1],
            height
          };
        }
      }

      isActive.value = false;
      showList.value = false;

      positiongetTimer.value = setInterval(() => {
        positiongetFlag.value = true;
        clearInterval(positiongetTimer.value);
      }, 1000);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 添加鼠标移动事件监听
  handler.setInputAction((event: any) => {
    const pickedObject = viewer.value!.scene.pick(event.endPosition);
    const canvas = viewer.value!.scene.canvas;

    if (pickedObject) {
      canvas.style.cursor = 'pointer';
    } else {
      canvas.style.cursor = 'default';
    }

    // if (Cesium.defined(pickedObject) && pickedObject.id) {
    //   const entity = pickedObject.id;
    //   // 判断是否是图片实体
    //   if (entity.rectangle && entity.rectangle.material instanceof Cesium.ImageMaterialProperty) {
    //     canvas.style.cursor = 'pointer';
    //   } else {
    //     canvas.style.cursor = 'default';
    //   }
    // } else {
    //   canvas.style.cursor = 'default';
    // }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 监听HomeButton事件
  viewer.value.homeButton.viewModel.command.beforeExecute.addEventListener((commandInfo) => {
    commandInfo.cancel = true; // 取消HomeButton事件的默认行为
    flyToPosition(flyToPositionArr.value.longitude, flyToPositionArr.value.latitude, flyToPositionArr.value.altitude);
  });
};

// 新增图片点击处理函数
const handleImageClick = (entity: Cesium.Entity) => {
  // 重置所有实体状态
  entityRefs.value.forEach((item) => {
    item.isActive = false;
    item.currentHeight = item.baseHeight; // 恢复基础高度
    if (entity.name !== item.imgName) {
      const entityObj = viewer.value!.entities.values.find((e) => e.name === item.imgName);
      if (entityObj?.rectangle) {
        entityObj.rectangle.height = new Cesium.ConstantProperty(item.baseHeight);
      }
    }
  });

  const targetIndex = entityRefs.value.findIndex((item) => item.imgName === entity.name);

  if (targetIndex !== -1) {
    entityRefs.value[targetIndex].isActive = true;

    // 提升高度实现置顶
    entityRefs.value[targetIndex].currentHeight = (entityRefs.value.length + 1) / 10;
    // 更新实体高度
    const rect = viewer.value!.entities.getById(entity.id)?.rectangle;
    if (rect) {
      rect.height = new Cesium.ConstantProperty(entityRefs.value[targetIndex].currentHeight);
    }
    // 自动滚动到对应位置（可选）
    // const listContainer = document.getElementById('checklist');
    // const targetItem = listContainer?.children[targetIndex];
    // targetItem?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
};

// 添加图片方法
const addImg = (arr, url, index) => {
  if (!viewer.value) return;

  // 计算地面覆盖范围
  const gsd = (arr.altitude * arr.sensorWidth) / (arr.focalLength * arr.imageWidth);
  const groundWidth = gsd * arr.imageWidth;
  const groundHeight = gsd * arr.imageHeight;

  // 转换为经纬度跨度
  const metersPerDegree = 111320;
  const deltaLon = groundWidth / 2 / (metersPerDegree * Math.cos(Cesium.Math.toRadians(arr.latitude)));
  const deltaLat = groundHeight / 2 / metersPerDegree;

  // 创建 Rectangle
  const rectangle = Cesium.Rectangle.fromDegrees(
    arr.longitude - deltaLon,
    arr.latitude - deltaLat,
    arr.longitude + deltaLon,
    arr.latitude + deltaLat
  );

  // 添加实体
  let entity = viewer.value.entities.add({
    name: arr.imgName, // 添加名称属性
    rectangle: {
      coordinates: rectangle,
      material: new Cesium.ImageMaterialProperty({
        image: url
      }),
      rotation: Cesium.Math.toRadians(-arr.heading),
      height: index,
      extrudedHeight: 0
    }
  });

  entityRefs.value.push({
    type: true,
    longitude: arr.longitude,
    latitude: arr.latitude,
    altitude: arr.altitude,
    imgName: arr.imgName,
    isActive: false,
    baseHeight: index, // 存储基础高度
    currentHeight: index // 当前显示高度
  });
};

// 相机视角定位
const flyToPosition = (longitude, latitude, altitude) => {
  if (!viewer.value) return;
  // 定位到图片中心
  viewer.value.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      longitude,
      latitude,
      altitude + 100 // 抬升视角
    ),
    orientation: {
      pitch: Cesium.Math.toRadians(-90),
      roll: 0
    }
  });
};

// 获取巡检列表
const getUAVcheckInfo2AddEntity = async (id) => {
  getUAVcheckInfo(id).then(async (res) => {
    viewer.value?.entities.removeAll();
    if (res.code === 200) {
      drawerInfo.value = res.data;
      drawerInfoID.value = [{ id: res.data.id, number: res.data.number }];
      if (res.data.question == questionFlag.value) {
        drawerInfoTimer.value = setInterval(() => {
          getUAVcheckInfo2AddEntity(id);
          clearInterval(drawerInfoTimer.value);
        }, 1000);
        if (entityRefs.value.length == 0) {
          console.log(entityRefs.value);
          ImageAdd2Layer(res);
        }
      } else {
        entityRefs.value = [];
        ImageAdd2Layer(res);
      }
    }
  });
};

const ImageAdd2Layer = async (res) => {
  for (const [index, item] of res.data.imgList.entries()) {
    drawerInfo.value.newImgUrl = [];
    drawerInfo.value.newImgUrl.push(item.newImgUrl);
    let position = {
      longitude: item.location.split(',')[0] * 1, // 中心经度
      latitude: item.location.split(',')[1] * 1, // 中心纬度
      altitude: item.height * 1 // 飞行高度（米）
    };
    const result = transformCoordinate(position.longitude, position.latitude);
    // 处理图片数据，例如添加到地图上
    let arr = {
      longitude: result[0], // 中心经度
      latitude: result[1], // 中心纬度
      altitude: item.height * 1, // 飞行高度（米）
      focalLength: 8.8, // 焦距（mm）
      sensorWidth: (36 * 8.8) / 35, // 传感器宽度（mm）
      imageWidth: 5472, // 图片宽度（像素）
      imageHeight: 3648, // 图片高度（像素）
      heading: 0, // 航向角（度）
      imgName: item.imgName
    };
    if (index === 0) {
      flyToPositionArr.value = arr;
      flyToPosition(flyToPositionArr.value.longitude, flyToPositionArr.value.latitude, flyToPositionArr.value.altitude);
    }
    // 使用示例
    try {
      const { blobUrl, canvas } = await rotateNetworkImage(item.newImgUrl, item.yaw);
      arr.imageWidth = canvas.width;
      arr.imageHeight = canvas.height;
      if (blobUrl) {
        addImg(arr, blobUrl, (res.data.imgList.length - index) / 10);
      }
    } catch (error) {
      console.error('处理图片时出错:', error);
    }
  }
};

// 坐标转化
const transformCoordinate = (lng, lat) => {
  const result = gcoord.transform([lng, lat], 'WGS84', 'GCJ02');
  return result;
};

const transformCoordinate2 = (lng, lat) => {
  const result = gcoord.transform([lng, lat], 'GCJ02', 'WGS84');
  return result;
};

const rotateNetworkImage = async (imageUrl, degrees) => {
  try {
    // 1. 加载网络图片
    const img = await loadImage(imageUrl);

    // 2. 创建Canvas并旋转
    const { canvas, ctx } = rotateImage(img, degrees);
    // 质量优化
    setupHighQuality(ctx);

    // 填充背景（可选）
    fillBackground(ctx);

    // 执行旋转绘制
    drawRotatedImage(ctx, img, degrees);

    // 3. 生成临时路径（Data URL 或 Blob URL）
    // const dataUrl = canvas.toDataURL('image/png', 0.9);
    // console.log(dataUrl);
    // 或生成Blob URL：
    const blobUrl = await canvasToBlobUrl(canvas);

    return { blobUrl, canvas };
  } catch (error) {
    console.error('处理失败:', error);
    return null;
  }
};

// 加载图片并处理跨域
const loadImage = (url) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous'; // 解决跨域问题（需服务器支持CORS）
    img.onload = () => resolve(img);
    img.onerror = (e) => reject(new Error('图片加载失败'));
    img.src = url;
  });
};

// 旋转图片并返回Canvas
const rotateImage = (img, degrees) => {
  // const radians = (degrees * Math.PI) / 180;

  // // 计算旋转后的新尺寸
  // const cos = Math.abs(Math.cos(radians));
  // const sin = Math.abs(Math.sin(radians));
  // const newWidth = img.width * cos + img.height * sin;
  // const newHeight = img.width * sin + img.height * cos;

  // // 创建Canvas
  // const canvas = document.createElement('canvas');
  // canvas.width = newWidth;
  // canvas.height = newHeight;
  // const ctx = canvas.getContext('2d');

  // // 平移至中心并旋转
  // ctx.translate(newWidth / 2, newHeight / 2);
  // ctx.rotate(radians);
  // ctx.drawImage(img, -img.width / 2, -img.height / 2);
  const { width, height } = calculateRotatedSize(img.width, img.height, degrees);
  const canvas = document.createElement('canvas');
  canvas.width = Math.ceil(width);
  canvas.height = Math.ceil(height);
  const ctx = canvas.getContext('2d');

  // 方法1：清除画布为全透明
  ctx.clearRect(0, 0, width, height);

  return {
    canvas,
    ctx
  };
};
const calculateRotatedSize = (width, height, angle) => {
  const rad = (angle * Math.PI) / 180;

  const sin = Math.abs(Math.sin(rad));
  const cos = Math.abs(Math.cos(rad));

  return {
    width: width * cos + height * sin,
    height: width * sin + height * cos
  };
};
const fillBackground = (ctx, color = 'white') => {
  ctx.fillStyle = 'rgba(0, 0, 0, 0)';
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
};

const setupHighQuality = (ctx) => {
  ctx.imageSmoothingEnabled = true;
  ctx.imageSmoothingQuality = 'high'; // 最高质量插值
  ctx.globalCompositeOperation = 'copy'; // 避免混合干扰
};

const drawRotatedImage = (ctx, image, angle) => {
  const canvas = ctx.canvas;
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;

  ctx.save();
  ctx.translate(centerX, centerY);
  ctx.rotate((angle * Math.PI) / 180);
  ctx.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height);
  ctx.restore();
};

// 转换为Blob URL（可选）
const canvasToBlobUrl = (canvas) => {
  return new Promise((resolve) => {
    canvas.toBlob(
      (blob) => {
        const blobUrl = URL.createObjectURL(blob);
        resolve(blobUrl);
      },
      'image/png',
      0.9
    );
  });
};

const goBack = () => {
  localStorage.removeItem('shouldNavigate');
  localStorage.removeItem('itemId');
  router.push({ path: '/ai/UAVinspection' });
};

const saveExport = async () => {
  const data = await putUAVcheckInfo({ id: drawerInfo.value.id, question: drawerInfo.value.question });
  if (data.code == 200) {
    ElMessage.success('文件保存成功');
    router.back();
  }
};

const handleExport = async () => {
  const loading = ElLoading.service({
    text: '正在生成报告，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  try {
    drawerInfoID.value.forEach(async (item) => {
      const response = await exportUAVcheck({ id: item.id });

      // 创建 Blob 对象并下载
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const downloadUrl = window.URL.createObjectURL(blob);

      // 创建隐藏的下载链接
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', `巡检报告_${item.number}.docx`);
      document.body.appendChild(link);
      link.click();

      // 清理资源
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
    });
  } catch (error) {
    ElMessage.error('文件导出失败');
  }
  loading.close();
};

const changelayer = (index, type) => {
  viewer.value.imageryLayers._layers[index].show = layerRefs.value[index].type = !type;
};

const changeEntity = (index, type) => {
  viewer.value.entities.values[index].show = entityRefs.value[index].type = !type;
};

// 切换列表显示
const toggleList = () => {
  showList.value = !showList.value;
  isActive.value = !isActive.value;
};

const clearStorage = () => {
  localStorage.removeItem('shouldNavigate');
  localStorage.removeItem('itemId');
};

onMounted(async () => {
  if (inspectionId.value) {
    getUAVcheckInfo2AddEntity(inspectionId.value);
  }
  await initCesium();
  window.addEventListener('beforeunload', clearStorage);
  window.addEventListener('unload', clearStorage); // 补充兼容性
});

onUnmounted(() => {
  window.removeEventListener('beforeunload', clearStorage);
  window.removeEventListener('unload', clearStorage);
});

onBeforeUnmount(() => {
  if (handler) {
    handler.destroy(); // 正确销毁事件处理器
  }
  viewer.value?.destroy();
  window.addEventListener('beforeunload', clearStorage);
  window.addEventListener('unload', clearStorage); // 补充兼容性
});

// 暴露变量
// defineExpose({
//   initCesium,
//   getUAVcheckInfo2AddEntity
// });
</script>

<style>
#cesiumContainer {
  width: 1000px;
  height: 100%;
  margin: 0 auto;
  background-color: #000;
  /* border-radius: 10px; */
  overflow: hidden;
}
.cesium-viewer-bottom,
.cesium-viewer-animationContainer,
.cesium-viewer-timelineContainer,
.cesium-viewer-toolbar {
  /* display: none; */
}
.cesium-viewer-bottom {
  display: none;
}

.InfoMainBody .el-textarea__inner {
  border: 1px solid #000 !important;
  border-radius: 0 !important;
  border-top: 0px;
}
</style>
<style scoped>
.export-btn,
.upload-btn ::v-deep .el-button {
  background: linear-gradient(45deg, #1a2840, #0d1a2f);
  border: 1px solid rgba(64, 158, 255, 0.3);
  color: #66b1ff;
  transition: all 0.3s;
}

.export-btn:hover,
.upload-btn ::v-deep .el-button:hover {
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);
  transform: translateY(-2px);
}

.position-info {
  position: absolute;
  top: 20px;
  left: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  border-radius: 5px;
  z-index: 999;
  width: 280px;
  box-shadow: 0 0px 10px #fff;
}

.position-info_item {
  position: absolute;
  top: 20px;
  /* left: 10px; */
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  z-index: 999;
  box-shadow: 0 0px 10px #fff;
}

/* 影像选择 */
.cesium-layer {
  position: absolute;
  top: 60px;
  right: 106px;
  z-index: 100;
}

.cesium-layer_btn {
  box-sizing: border-box;
  width: 32px;
  height: 32px;
  border-radius: 14%;
  padding: 0;
  vertical-align: middle;
  background: #303336;
  border: 1px solid #444;
  cursor: pointer;
}

/* 悬停状态 */
.cesium-layer_btn:hover {
  border: 1px solid #b7dae8;
  box-shadow:
    0px 0px 10px 1px rgba(33, 150, 243, 0.5),
    0 0 30px rgba(33, 150, 243, 1) inset;
}

/* 点击涟漪效果 */
.cesium-layer_btn.active {
  border: 1px solid #ecb869;
}

.options-list {
  position: absolute;
  top: 110px;
  right: 142px;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  padding: 10px 20px;
  width: 175px;
  border-radius: 5px;
  z-index: 999;
  color: #fff;
  box-shadow: 0 0px 10px #fff;
}

.options-list .item {
  display: flex;
  align-items: center;
}

.InfoMainBody {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  padding-top: 20px;
}

.InfoMainBody .btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.InfoMainBody .infoTitle {
  text-align: center;
  font-size: 40px;
  font-weight: 600;
  margin-bottom: 40px;
}
.checkboxItem {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 30px;
  height: 30px;
}

.miniWindow {
  position: relative;
  padding: 10px 0;
  /* position: fixed;
  left: 10px;
  bottom: 10px; */
  width: 1200px;
  height: 618px;
  /* background-color: #000; */
  /* border: 1px solid #000; */
  /* border-radius: 10px; */
  /* overflow: hidden; */
}
.miniWindow .vdr-container {
  padding: 4px;
  border-color: #000;
  border-style: dashed;
  cursor: pointer;
}

.tabelLine {
  display: flex;
  justify-content: space-around;
  border: 1px solid #000;
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-weight: 600;
}

.tabelItem {
  border-right: 1px solid #000;
  width: 100%;
}
.tabelItem1 {
  border-right: 0;
}
.imgLine {
  border: 1px solid #000;
}
.imgLine img {
  width: 1000px;
  margin: 0 auto;
  display: block;
  margin: 0 auto;
  margin-bottom: 10px;
}
.tabelLine1 {
  border-top: 0;
}
</style>
/* 选择框样式开始 */
<style scoped>
#checklist {
  position: absolute;
  top: 50%;
  left: 10px;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  padding: 10px 20px;
  width: 280px;
  max-height: 300px;
  overflow-y: auto;
  border-radius: 5px;
  z-index: 999;
  color: #fff;
  box-shadow: 0 0px 10px #fff;
}

/* 修改滚动条宽度和颜色 */
::-webkit-scrollbar {
  width: 0px;
  background-color: #000;
}

#checklist .item {
  display: flex;
  align-items: center;
}
.checkBox {
  width: 30px;
  height: 30px;
  margin-right: 20px;
}
.checkboxItem {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 30px;
  height: 30px;
}
.neon-checkbox {
  --primary: #00ffaa;
  --primary-dark: #00cc88;
  --primary-light: #88ffdd;
  --size: 30px;
  width: 30px;
  height: 30px;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
}

.neon-checkbox input {
  display: none;
}

.neon-checkbox__frame {
  position: relative;
  width: 100%;
  height: 100%;
}

.neon-checkbox__box {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 4px;
  border: 2px solid var(--primary-dark);
  transition: all 0.4s ease;
}

.neon-checkbox__check-container {
  position: absolute;
  inset: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.neon-checkbox__check {
  width: 80%;
  height: 80%;
  fill: none;
  stroke: var(--primary);
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-dasharray: 40;
  stroke-dashoffset: 40;
  transform-origin: center;
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

.neon-checkbox__glow {
  position: absolute;
  inset: -2px;
  border-radius: 6px;
  background: var(--primary);
  opacity: 0;
  filter: blur(8px);
  transform: scale(1.2);
  transition: all 0.4s ease;
}

.neon-checkbox__borders {
  position: absolute;
  inset: 0;
  border-radius: 4px;
  overflow: hidden;
}

.neon-checkbox__borders span {
  position: absolute;
  width: 40px;
  height: 1px;
  background: var(--primary);
  opacity: 0;
  transition: opacity 0.4s ease;
}

.neon-checkbox__borders span:nth-child(1) {
  top: 0;
  left: -100%;
  animation: borderFlow1 2s linear infinite;
}

.neon-checkbox__borders span:nth-child(2) {
  top: -100%;
  right: 0;
  width: 1px;
  height: 40px;
  animation: borderFlow2 2s linear infinite;
}

.neon-checkbox__borders span:nth-child(3) {
  bottom: 0;
  right: -100%;
  animation: borderFlow3 2s linear infinite;
}

.neon-checkbox__borders span:nth-child(4) {
  bottom: -100%;
  left: 0;
  width: 1px;
  height: 40px;
  animation: borderFlow4 2s linear infinite;
}

.neon-checkbox__particles span {
  position: absolute;
  width: 4px;
  height: 4px;
  background: var(--primary);
  border-radius: 50%;
  opacity: 0;
  pointer-events: none;
  top: 50%;
  left: 50%;
  box-shadow: 0 0 6px var(--primary);
}

.neon-checkbox__rings {
  position: absolute;
  inset: -20px;
  pointer-events: none;
}

.neon-checkbox__rings .ring {
  position: absolute;
  inset: 0;
  border-radius: 50%;
  border: 1px solid var(--primary);
  opacity: 0;
  transform: scale(0);
}

.neon-checkbox__sparks span {
  position: absolute;
  width: 20px;
  height: 1px;
  background: linear-gradient(90deg, var(--primary), transparent);
  opacity: 0;
}

/* Hover Effects */
.neon-checkbox:hover .neon-checkbox__box {
  border-color: var(--primary);
  transform: scale(1.05);
}

/* Checked State */
.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__box {
  border-color: var(--primary);
  background: rgba(0, 255, 170, 0.1);
}

.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__check {
  stroke-dashoffset: 0;
  transform: scale(1.1);
}

.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__glow {
  opacity: 0.2;
}

.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__borders span {
  opacity: 1;
}

/* Particle Animations */
.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__particles span {
  animation: particleExplosion 0.6s ease-out forwards;
}

.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__rings .ring {
  animation: ringPulse 0.6s ease-out forwards;
}

.neon-checkbox input:checked ~ .neon-checkbox__frame .neon-checkbox__sparks span {
  animation: sparkFlash 0.6s ease-out forwards;
}

.textarea-with-button {
  position: relative;
}

.save-report-button {
  position: absolute;
  right: 10px;
  bottom: 10px;
  z-index: 1;
}

/* Animations */
@keyframes borderFlow1 {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(200%);
  }
}

@keyframes borderFlow2 {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(200%);
  }
}

@keyframes borderFlow3 {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-200%);
  }
}

@keyframes borderFlow4 {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-200%);
  }
}

@keyframes particleExplosion {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0;
  }
  20% {
    opacity: 1;
  }
  100% {
    transform: translate(calc(-50% + var(--x, 20px)), calc(-50% + var(--y, 20px))) scale(0);
    opacity: 0;
  }
}

@keyframes ringPulse {
  0% {
    transform: scale(0);
    opacity: 1;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

@keyframes sparkFlash {
  0% {
    transform: rotate(var(--r, 0deg)) translateX(0) scale(1);
    opacity: 1;
  }
  100% {
    transform: rotate(var(--r, 0deg)) translateX(30px) scale(0);
    opacity: 0;
  }
}

/* Particle Positions */
.neon-checkbox__particles span:nth-child(1) {
  --x: 25px;
  --y: -25px;
}
.neon-checkbox__particles span:nth-child(2) {
  --x: -25px;
  --y: -25px;
}
.neon-checkbox__particles span:nth-child(3) {
  --x: 25px;
  --y: 25px;
}
.neon-checkbox__particles span:nth-child(4) {
  --x: -25px;
  --y: 25px;
}
.neon-checkbox__particles span:nth-child(5) {
  --x: 35px;
  --y: 0px;
}
.neon-checkbox__particles span:nth-child(6) {
  --x: -35px;
  --y: 0px;
}
.neon-checkbox__particles span:nth-child(7) {
  --x: 0px;
  --y: 35px;
}
.neon-checkbox__particles span:nth-child(8) {
  --x: 0px;
  --y: -35px;
}
.neon-checkbox__particles span:nth-child(9) {
  --x: 20px;
  --y: -30px;
}
.neon-checkbox__particles span:nth-child(10) {
  --x: -20px;
  --y: 30px;
}
.neon-checkbox__particles span:nth-child(11) {
  --x: 30px;
  --y: 20px;
}
.neon-checkbox__particles span:nth-child(12) {
  --x: -30px;
  --y: -20px;
}

/* Spark Rotations */
.neon-checkbox__sparks span:nth-child(1) {
  --r: 0deg;
  top: 50%;
  left: 50%;
}
.neon-checkbox__sparks span:nth-child(2) {
  --r: 90deg;
  top: 50%;
  left: 50%;
}
.neon-checkbox__sparks span:nth-child(3) {
  --r: 180deg;
  top: 50%;
  left: 50%;
}
.neon-checkbox__sparks span:nth-child(4) {
  --r: 270deg;
  top: 50%;
  left: 50%;
}

/* Ring Delays */
.neon-checkbox__rings .ring:nth-child(1) {
  animation-delay: 0s;
}
.neon-checkbox__rings .ring:nth-child(2) {
  animation-delay: 0.1s;
}
.neon-checkbox__rings .ring:nth-child(3) {
  animation-delay: 0.2s;
}
/* 选择框样式结束 */
</style>
